<template>
  <div class="register">
    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
      <h3 class="title">校园论坛系统</h3>
      <el-form-item  label="账号" prop="studentName">
        <el-input v-model="registerForm.studentName" type="text" auto-complete="off" placeholder="账号">
          <template #prefix>
            <el-icon>
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item  label="密码" prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleRegister"
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          auto-complete="off"
          placeholder="确认密码"
          @keyup.enter.native="handleRegister"
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item  label="昵称" prop="nickName">
        <el-input v-model="registerForm.nickName" type="text" auto-complete="off" placeholder="昵称">
          <template #prefix>
            <el-icon><UserFilled /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item  label="手机" prop="phonenumber">
        <el-input v-model="registerForm.phonenumber" type="text" auto-complete="off" placeholder="账号">
          <template #prefix>
            <el-icon><Iphone /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="性别" prop="grade">
        <el-select v-model="registerForm.sex" filterable placeholder="请选择性别">
          <el-option
            v-for="sex in sexs"
            :key="sex.dictValue"
            :label="sex.dictLabel"
            :value="sex.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学校" prop="schoolId">
        <el-select v-model="registerForm.schoolId" filterable @change="queryChangeSchoolSelect()" placeholder="请选择学校">
          <el-option
            v-for="school in schoolList"
            :key="school.id"
            :label="school.name"
            :value="school.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学院" prop="collegeId">
        <el-select v-model="registerForm.collegeId" :disabled="!registerForm.schoolId" filterable @change="queryChangeCollegeSelect()" placeholder="请选择学院">
          <el-option
            v-for="college in showCollegeList"
            :key="college.id"
            :label="college.name"
            :value="college.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专业" prop="specialtyId">
        <el-select v-model="registerForm.specialtyId" :disabled="!registerForm.collegeId" filterable placeholder="请选择专业">
          <el-option
            v-for="specialty in showSpecialtyList"
            :key="specialty.id"
            :label="specialty.name"
            :value="specialty.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="registerForm.grade" filterable placeholder="请选择年级">
          <el-option
            v-for="grade in grades"
            :key="grade.dictValue"
            :label="grade.dictLabel"
            :value="grade.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" type="email" auto-complete="off" placeholder="邮箱">
          <template #prefix>
            <el-icon><Suitcase /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item  label="验证码" prop="code" v-if="captchaEnabled">
        <el-input
          v-model="registerForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleRegister"
        >
          <template #prefix>
            <el-icon><Message /></el-icon>
          </template>
        </el-input>
        <div class="register-code">
          <el-button style="width: 100%;height: 100%;" :disabled="isDisable" type="primary" @click="getCode()">{{ disableTime != 0 ? disableTime+'s' : '获取验证码' }}</el-button>
        </div>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleRegister"
        >
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right;">
          <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>Copyright © 2024 fanlong All Rights Reserved.  赣ICP备2024040628号-1</span>
    </div>
  </div>
</template>

<script>
import { getEmailCodeImg, register } from "@/api/login";
import {ElMessage} from 'element-plus';
import {getDictsForRegister} from '@/api/system/dict/data'
import {regListSchool} from '@/api/forum/school';
import {regListCollege} from '@/api/forum/college';
import {regListSpecialty} from '@/api/forum/specialty';
// import {listSchool,regListSchool} from '@/api/forum/school';
// import {listCollege,regListCollege} from '@/api/forum/college';
// import {listSpecialty,regListSpecialty} from '@/api/forum/specialty';

export default {
  name: "Register",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const checkoutEmail = (rule, value, callback) => {
      if (!this.validateEmail(value)) {
        callback(new Error("邮箱格式不正确"));
      } else {
        callback();
      }
    };
    return {
      codeUrl: "",
      sexs: null,
      grades: null,
      registerForm: {
        studentName: "",
        password: "",
        confirmPassword: "",
        grade: null,
        email: "",
        code: "",
        uuid: "",
        schoolId: null,
        collegeId: null,
        specialtyId: null
      },
      registerRules: {
        studentName: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
        sex: [
          { required: true, trigger: "blur", message: "请再次选择您的性别" },
        ],
        grade: [
          { required: true, trigger: "blur", message: "请再次选择您的年级" },
        ],
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        schoolId: [
          { required: true, message: "学校id不能为空", trigger: "blur" }
        ],
        collegeId: [
          { required: true, message: "学院id不能为空", trigger: "blur" }
        ],
        specialtyId: [
          { required: true, message: "专业id不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入您的邮箱" },
          { required: true, validator: checkoutEmail, trigger: "blur" }
          // { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      captchaEnabled: true,
      isDisable: false,
      disableTime: 0,
      interval: null,
      schoolList:[],
      collegeList:[],
      showCollegeList:[],
      specialtyList:[],
      showSpecialtyList:[]
    };
  },
  created() {
    this.getDicts('forum_grade');
    this.getDicts('sys_user_sex');
    this.getSchoolList();
    this.getCollegeList();
    this.getSpecialtyList();
  },
  methods: {
    //查询时点击学校按钮时筛选学院信息
    queryChangeSchoolSelect(){
      this.registerForm.collegeId=null;
      this.registerForm.specialtyId=null;
      // this.queryChangeCollegeSelect();
      this.getCollegeListForSchoolId(this.registerForm.schoolId);
    },
    //查询时点击学院按钮时筛选专业信息
    queryChangeCollegeSelect(){
      this.registerForm.specialtyId=null;
      this.getSpecialtyListForCollegeId(this.registerForm.collegeId);
    },
    /** 根据学院专业管理列表 */
    getSpecialtyListForCollegeId(collegeId) {
      var tempSpecialtyList = [];
      for(var i=0;i<this.specialtyList.length;i++){
        if(collegeId===this.specialtyList[i].collegeId){
          tempSpecialtyList.push(this.specialtyList[i]);
        }
      }
      this.showSpecialtyList=tempSpecialtyList;
    },
    /** 查询专业管理列表 */
    getSpecialtyList() {
      this.loading = true;
      regListSpecialty().then(response => {
        this.specialtyList = response.rows;
        this.showSpecialtyList = response.rows;
        this.loading = false; 
      });
    },
    /** 根据学校筛选学院管理列表 */
    getCollegeListForSchoolId(schoolId) {
      var tempCollegeList = [];
      for(var i=0;i<this.collegeList.length;i++){
        if(schoolId===this.collegeList[i].schoolId){
          tempCollegeList.push(this.collegeList[i]);
        }
      }
      this.showCollegeList=tempCollegeList;
    },
    /** 查询学院管理列表 */
    getCollegeList() {
      this.loading = true;
      regListCollege().then(response => {
        this.collegeList = response.rows;
        this.showCollegeList = response.rows;
        this.loading = false;
      });
    },
    /** 查询学校管理列表 */
    getSchoolList() {
      this.loading = true;
      regListSchool().then(response => {
        this.schoolList = response.rows;
        this.loading = false;
      });
    },
    //获取字典
    getDicts(dictName){
      getDictsForRegister(dictName).then(res => {
        if(dictName == 'forum_grade'){
          this.grades = res.data;
        }else if(dictName == 'sys_user_sex'){
          this.sexs = res.data;
        }
      });
    },
    validateEmail(email) {
      var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return re.test(email);
    },
    getCode() {
      if(this.registerForm.email!=null && this.registerForm.email!=''){
        if(this.validateEmail(this.registerForm.email)){
          var query = {
            email : this.registerForm.email
          }
          getEmailCodeImg(query).then(res => {
            if(res.code==200){
              this.isDisable = true;
              this.disableTime = 120;
              this.interval = setInterval(() => {
                this.disableTime = this.disableTime-1;
              },1000)
              ElMessage({
                message: res.msg,
                type: 'success'
              });
            }
          });
        }else{
          ElMessage.error("邮箱格式有误，请输入正确邮箱。");
        }
      }else{
        ElMessage.error("请输入邮箱后，在点击发送验证码。");
      }
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true;
          register(this.registerForm).then(res => {
            const studentName = this.registerForm.studentName;
            if(res.code == 330){
              this.loading = false;
            }else if(res.code == 200){
              this.$alert("<font color='red'>恭喜你，您的账号 " + studentName + " 注册成功！</font>", '系统提示', {
                dangerouslyUseHTMLString: true,
                type: 'success'
              }).then(() => {
                this.$router.push("/login");
              }).catch(() => {});
            }
          }).catch(() => {
            this.loading = false;
          })
        }
      });
    }
  },
  watch: {
    'disableTime': {
      handler() {
        if (this.disableTime == 0) {
          clearTimeout(this.interval);
        }
      },
      // 强制立即执行回调
      immediate: true
    }
  }
}

</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("../assets/images/background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
  font-weight: bolder;
  font-size: 24px;
}

.register-form {
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.7);
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.register-code {
  width: 33%;
  height: 38px;
  float: right;
  margin-left: 10px;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.register-code-img {
  height: 38px;
}
</style>
